import express, { Request, Response } from 'express';
import { query } from '../database';
import { authenticateToken } from '../middleware/auth';

const router = express.Router();

// 获取仪表板统计信息
router.get('/stats', authenticateToken, async (req: Request, res: Response) => {
  try {
    // 总资产数量
    const totalAssetsResult = await query('SELECT COUNT(*) as total FROM assets');
    const totalAssets = (totalAssetsResult as any[])[0].total;

    // 总用户数量
    const totalUsersResult = await query('SELECT COUNT(*) as total FROM users');
    const totalUsers = (totalUsersResult as any[])[0].total;

    // 计算总价值
    const totalValueResult = await query('SELECT COALESCE(SUM(price), 0) as total FROM assets');
    const totalValue = (totalValueResult as any[])[0].total;

    // 低库存项目数量（这里暂时用状态为'维修中'的资产作为低库存示例）
    const lowStockResult = await query(`
      SELECT COUNT(*) as total 
      FROM assets 
      WHERE status = '维修中'
    `);
    const lowStockItems = (lowStockResult as any[])[0].total;

    // 最近添加的资产
    const recentAssetsResult = await query(`
      SELECT id, name, category, status, created_at as createdAt
      FROM assets 
      ORDER BY created_at DESC 
      LIMIT 5
    `);
    const recentAssets = recentAssetsResult || [];

    res.json({
      success: true,
      data: {
        totalAssets,
        totalUsers,
        totalValue,
        lowStockItems,
        recentAssets
      }
    });

  } catch (error) {
    console.error('获取仪表板统计失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

export default router;
